import 'dart:async';
// import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
// import 'package:synchronized/synchronized.dart';
import '../../lib_basemodel/user/user.dart';
import '../../lib_baseview/global_notice/float/float_screen.dart';
import '../../lib_baseview/global_notice/global_notice.dart';
import '../../lib_baseview/root_page.dart';
import '../../lib_baseview/widget/dialogs.dart';
import '../../lib_network/old/result.dart';
import '../../lib_runtime/event_center.dart';
import '../../lib_runtime/event_constant.dart';
import '../../lib_runtime/global_config.dart';
import '../../lib_runtime/logger.dart';
import '../../lib_user/user_manager.dart';
import '../../m_main/main/main_page.dart';
import '../login_page_model.dart';
import '../model/login_args.dart';
import '../platforms/third_login_platform_interface.dart';
import 'login_listener.dart';
import 'login_storage.dart';

//苹果ID登陆回调
typedef appleIDLoginCallBack();

class LoginManager {
  var log = RLog.create("LoginManager");
  static final instance = LoginManager._();
  // final _lock = Lock();
  final LoginListener loginListener = LoginListener();
  var process_logining = false;

  //获取审核记录数据
  // UserApprovalRecordResp? userApprovalRecordResp;

  StreamSubscription<Event>? _eventSub;
  StreamSubscription<ConnectivityResult>? _connectivitySub;
  StreamSubscription<User?>? _userSub;

  bool isConnectNetwork(ConnectivityResult? r) {
    if (r == null) {
      return false;
    }
    return r == ConnectivityResult.ethernet ||
        r == ConnectivityResult.mobile ||
        r == ConnectivityResult.wifi;
  }

  LoginManager._() {
    log.printLog("LoginManager.<init>");

    if (_connectivitySub != null) {
      _connectivitySub = Connectivity().onConnectivityChanged.listen((event) {
        log.printLog("onConnectivityChanged $event");
        if (isConnectNetwork(event as ConnectivityResult?)) {
          if (!UserManager.instance.hasLogin()) {
            if (!process_logining) {
              // authLogin("onConnectivityChanged $event");
            }
          }
        }
      }) as StreamSubscription<ConnectivityResult>?;
    }

    _eventSub = eventCenter.subscribe(EventConstant.login).listen((event) {
      // if (event.data is LoginArgs) {
      //   LoginArgs loginArgs = event.data as LoginArgs;
      //   Reporter.login(loginArgs.userId);
      //   Reporter.track(TrackEvent.login, {
      //     "type": loginArgs.loginPlatform?.name ?? 'mobile',
      //     "is_success": true
      //   });
      // }
    });

    _userSub = UserManager.instance.listenUser().listen((event) {
      if (event is User) {
        // Reporter.userSet({
        //   'nickname': event.nickname,
        //   'birthday': event.birthday,
        //   'gender': event.gender,
        //   'age': event.age
        // });
        // Reporter.setSuperProperties({
        //   "is_leader": event.isLeader,
        //   "is_companion": event.isCompanion,
        //   "is_broker": event.isBroker,
        //   "is_host": event.isHost,
        //   "broker_id": event.brokerId.toInt(),
        //   "leader_id": event.leaderId.toInt(),
        //   "gid": event.gsGroupId.toInt()
        // });
      }
    });
  }

  void release() {
    _eventSub?.cancel();
    _connectivitySub?.cancel();
    _userSub?.cancel();
  }

  Future<bool> loginSuccessUpdateInfo(LoginType type, String token,
      {LoginPlatform? loginPlatform}) async {
    log.printLog("_notifyLogin $type  token:$token");
    UserManager.instance.setToken(token);
    bool result = await UserManager.instance.refreshUserInfo();
    if (!result) {
      await dismissLoadingDialog();
      return false;
    }
    User user = UserManager.instance.currentUser!;
    log.printLog("_notifyLogin $user");

    var autoLoginArgs = LoginArgs(
        type: type,
        userId: user.userId.toString(),
        token: token,
        // emUser: user.emUsername,
        // emPwd: user.emPwd,
        loginPlatform: loginPlatform,
        refreshToken: token);
    await LoginStorage.instance.saveLoginInfo(autoLoginArgs);
    await dismissLoadingDialog();
    await GlobalConfig.refreshConfInfo();
    await GlobalConfig.refreshSettings();
    return true;
  }

  ///登录成功之后需要跳转的页面
  loginSuccessJump() {
    User user = UserManager.instance.currentUser!;
    Widget? widget;
    if (user.birth != null) {
      widget = MainPage();
    } else {
      widget = Text("完善资料");
    }
  }

  // //获取是否有会长
  // Future<GetLeaderResp?> queryHasLeader() async {
  //   var result = (await TeamLeaderApi.instance.getLeaderInfo()).data;
  //   if (result != null) {
  //     return result;
  //   }
  //   return null;
  // }

  ///自动登录
  Future<Result<bool>> authLogin([String cause = ""]) async {
    process_logining = true;
    log.printLog("call authLogin() cause by $cause");

    log.printLog("real call authLogin() $cause");

    // return true;
    return SuccessResult(false);
    //   if (UserManager.instance.hasLogin()) {
    //     return SuccessResult(true);
    //   }

    //   LoginArgs? loginArgs = null;
    //   try {
    //     loginArgs = await LoginStorage.instance.readCurrLoginInfo();
    //     if (loginArgs != null) {
    //       log.printLog("read current login info = $loginArgs");
    //     } else {
    //       log.printLog("read current login info empty");
    //     }
    //   } catch (e) {
    //     log.printLog(e);
    //   }
    //   log.printLog("autoLogin $loginArgs");
    //   if (loginArgs == null || !loginArgs.enable()) {
    //     log.printLog("ignore autoLogin no saved login info");
    //     return ErrorResult(LoginException(-1, "no saved login info"));
    //   }
    //   log.printLog("call authLogin()/_retry _authLoginInternal");
    //   return await _authLoginInternal(loginArgs);
    // };
  }

  Future<Result<bool>> _authLoginInternal(LoginArgs loginArgs) async {
    // UserManager.instance.setToken(loginArgs.token);
    // BaseRspResult<RefreshTokenData>? response;
    // try {
    //   log.printLog("refreshToken token = ${loginArgs.refreshToken}");
    //   response = await LoginApi.instance.refreshToken(loginArgs.token);
    // } catch (e) {
    //   log.printLog("refreshToken fail $e");
    // }

    // if (response?.isSuccess ?? false) {
    //   ///自动登录成功之后再检查跟新版本和协议之后再跳转页面
    //   bool result = await loginSuccessUpdateInfo(
    //       LoginType.autoLogin, response!.data!.token,
    //       loginPlatform: loginArgs.loginPlatform);
    //   return SuccessResult(result);
    // } else {
    return SuccessResult(false);
    // }
  }

  // 手动登录
  Future<Result<bool>> login(LoginArgs loginArgs) async {
    // return await _lock.synchronized(() async {
    //   log.printLog("start login: $loginArgs");
    //   var response = await LoginApi.instance
    //       .smsAuth(loginArgs.phone, loginArgs.authCode, loginArgs.userInfoKey);
    //   if (!response.isSuccess) {
    //     showToast(response.errorMsg!);
    //     return ErrorResult(
    //         LoginException(response.errorCode, response.errorMsg));
    //   }
    //   var resultData = response.data!;
    //   bool result = await loginSuccessUpdateInfo(LoginType.sms, resultData.token,loginPlatform:loginArgs.loginPlatform);
    //   return SuccessResult(result);
    // });
    return SuccessResult(false);
  }

  // 退出登陆
  Future<bool> logout() async {
    log.printLog("start logout ${UserManager.instance.currentUid}");
    // return await _lock.synchronized(() async {
    //   GlobalNotice.dismiss();
    //   UserManager.instance.updateUserInfo(null);
    //   await LoginStorage.instance.clearLoginInfo();
    //   loginListener.onLogout?.call(UserManager.instance.currentUser);
    //   loginListener.onUpdateUserInfo?.call(null);
    //   rootNavigatorState.currentContext?.read<LoginPageModel>().clearAllInfo();
    //   // Reporter.logout();
    //   FloatScreen.dispose();
    //   return true;
    // });

    GlobalNotice.dismiss();
    UserManager.instance.updateUserInfo(null);
    await LoginStorage.instance.clearLoginInfo();
    loginListener.onLogout?.call(UserManager.instance.currentUser);
    loginListener.onUpdateUserInfo?.call(null);
    rootNavigatorState.currentContext?.read<LoginPageModel>().clearAllInfo();
    // Reporter.logout();
    FloatScreen.dispose();
    return true;
  }

  Future<bool> unRegister() async {
    // log.printLog("start unRegister ${UserManager.instance.currentUid}");
    // return await _lock.synchronized(() async {
    //   var result = await UserApi.instance.unRegisterAccount();
    //   if (result != null && result.isSuccess) {
    //     UserManager.instance.updateUserInfo(null);
    //     await LoginStorage.instance.clearLoginInfo();
    //     loginListener.onLogout?.call(UserManager.instance.currentUser);
    //     loginListener.onUpdateUserInfo?.call(null);
    //     return true;
    //   } else {
    //     return false;
    //   }
    // });
    return false;
  }
}
